package com.nageoffer.shortlink.admin.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageoffer.shortlink.admin.common.convention.exception.ClientException;
import com.nageoffer.shortlink.admin.common.enums.ErrorCodeEnum.UserErrorCodeEnum;
import com.nageoffer.shortlink.admin.dao.entity.UserDo;
import com.nageoffer.shortlink.admin.dao.mapper.Usermapper;
import com.nageoffer.shortlink.admin.dto.req.UserRegisterReqDto;
import com.nageoffer.shortlink.admin.dto.resp.UserRespDTO;
import com.nageoffer.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<Usermapper, UserDo> implements UserService {


    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;




    /**
     * 根据用户名查询用户信息
     * @param username
     * @return
     */
    @Override
    public UserRespDTO getUserByUsername(String username){
//       LambdaQueryWrapper<UserDo> eq = Wrappers.lambdaQuery(UserDo.class)
//                .eq(UserDo::getUsername,username);
//
//
//       UserDo userDo = baseMapper.selectOne(eq);
//        UserRespDTO userRespDTO = new UserRespDTO();
//        BeanUtils.copyProperties(userDo,userRespDTO);
//        return userRespDTO;
//    }
        LambdaQueryWrapper<UserDo> eq = Wrappers.lambdaQuery(UserDo.class).eq(UserDo::getUsername, username);
        UserDo userDo = baseMapper.selectOne(eq);
        UserRespDTO userRespDTO = new UserRespDTO();

        if (userDo == null) {
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }

        BeanUtils.copyProperties(userDo,userRespDTO);

        return userRespDTO;
    }

    /**
     * 判断用户是否存在
     * @param username
     * @return
     */
    @Override
    public Boolean hasUsername(String username) {

        return  !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    /**
     * 注册用户
     * @param requestParam
     */
    @Override
    public void register(UserRegisterReqDto requestParam) {
        //判断用户名是否存在
        if (hasUsername(requestParam.getUsername())) {
            //不存在抛出异常
            throw new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);
        }

        //存在存到数据库
        int insert = baseMapper.insert(BeanUtil.toBean(requestParam, UserDo.class));

        if(insert < 1){
            throw new ClientException(UserErrorCodeEnum.SAVE_USER_ERROR);
        }


    }
}
